<?php
/**
 * Created by PhpStorm.
 * User: 70767
 * Date: 2020/8/2
 * Time: 17:23
 */

namespace app\api\controller;

use app\common\logic\UserLogic;
use think\Db;
use think\Validate;
//header('Access-Control-Allow-Origin:*');
//header('Access-Control-Allow-Methods:*');
//header('Access-Control-Allow-Headers:*');
class Dfsubject extends Base
{
    /*
     * 初始化操作
     */
    public function _initialize()
    {
        $this->nocheckArr = ['get_subject_info','answer_subject','get_alls','get_subject_info_test','submit_msg','get_user_info','get_holiday'];
        parent::_initialize();
//        $this->End_Day = $this->Start_Day + 23 * 86400;
    }

    //开始时间
    private $Start_Day = 1602691200;//1602691200;//1600531200;//1600790400;
    //结束时间
    private $End_Day = 1605283199;//1598821200;//1598400681;//1598112001;//'2020-08-23 00:00:00';
    //活动最大天数
    private $Max_Day = 23;

    //隔离日期
    private $gq_arr = ['2020-10-01','2020-10-02','2020-10-03','2020-10-04','2020-10-05','2020-10-06','2020-10-07'];
    private $tm = [
        1=>[
            "id"=>1,
            "title"=>"东方证券成立于_____________。",
            "subject"=>["1998年3月","2001年3月"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>1
        ],
        2=>[
            "id"=>2,
            "title"=>"东方证券旗下有多少家全资子公司？",
            "subject"=>["6家","4家"],
            "answer"=>"0",
            "tips"=>"东方证券全资持有上海东证期货有限公司、上海东方证券资产管理有限公司、上海东方证券资本投资有限公司、东方金融控股（香港）有限公司、上海东方证券创新投资有限公司，东方证券承销保荐有限公司。除此以外，公司还作为第一大股东参股汇添富基金管理股份有限公司。",
            "type"=>1
        ],
        3=>[
            "id"=>3,
            "title"=>"东方证券于2015年3月23日成功登陆上交所，证券代码是_______________。",
            "subject"=>["600958","606958"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>1
        ],
        4=>[
            "id"=>4,
            "title"=>"东东方证券于___________________成功发行H股。",
            "subject"=>["2016年7月8日","2018年8月7日"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>1
        ],
        5=>[
            "id"=>5,
            "title"=>"东方证券是行业内第几家实现A+H股的上市券商？",
            "subject"=>["第五家","第七家"],
            "answer"=>"0",
            "tips"=>"公司于2015年3月23日登陆上交所，2016年7月8日成功发行H股，成为行业内第五家A+H股上市券商。",
            "type"=>1
        ],
        6=>[
            "id"=>6,
            "title"=>"截止目前，东方证券分支机构已覆盖81个城市，31个省自治区直辖市，分支机构的数量已经达到______________。",
            "subject"=>["180家","168家"],
            "answer"=>"1",
            "tips"=>"",
            "type"=>1
        ],
        7=>[
            "id"=>7,
            "title"=>"东方证券目前有_____________名员工？",
            "subject"=>["5000余","3000余"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>1
        ],
        8=>[
            "id"=>8,
            "title"=>"东方证券的愿景是",
            "subject"=>["成为具有国内一流核心竞争力，为客户提供综合金融服务的现代投资银行","成为一家业内领先的证券公司"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>1
        ],
        9=>[
            "id"=>9,
            "title"=>"9、	公司的品牌标识是：",
            "subject"=>["https://games.jbxiong.com/images/title/91.png","https://games.jbxiong.com/images/title/92.png"],
            "answer"=>"0",
            "tips"=>"2015年公司上市之际，东方证券品牌标识进行了优化调整，四片花瓣呈现更为稳定的状态，字体更加舒展，呈现大气、现代的公司形象。",
            "type"=>1,
            "isimg"=>2
        ],
        10=>[
            "id"=>10,
            "title"=>"东方证券的品牌理念是什么？",
            "subject"=>["永无止境的追求财富","美好生活不仅仅只有财富，还包括真爱、健康和快乐，东方证券与您一起追寻美好，悦享美好"],
            "answer"=>"1",
            "tips"=>"",
            "type"=>1,
        ],
        11=>[
            "id"=>11,
            "title"=>"中国证监会主席易会满指出，健康良好的行业文化是行稳致远的立身之本，主要强调了哪四点",
            "subject"=>["合规是底线、诚信是义务、专业是特色、稳健是保证","明确目标，压实责任，挂图作战、落实到位"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>1,
        ],
        12=>[
            "id"=>12,
            "title"=>"东方证券连续几年获得监管评级A类AA级或A类A级",
            "subject"=>["11年","5年"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>1,
        ],
        13=>[
            "id"=>13,
            "title"=>"我们把“朝阳中的四片花瓣”作为东方证券的标识，象征着美好生活的多重含义，四片花瓣被霞光渲染成通体的“东方红”，寓示美好生活盎然绽放，生生不息，这四片花瓣分别代表了什么？",
            "subject"=>["财富、健康、快乐、真爱","金钱、身份、爱情、人生价值"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>1,
        ],
        14=>[
            "id"=>14,
            "title"=>"东方证券品牌视觉辅助型取自“东方朝阳”，以下描述正确的是",
            "subject"=>["金色代表财富","红色渐变代表真爱、健康和快乐"],
            "answer"=>"0,1",
            "tips"=>"“东方朝阳”的概念：一轮正在东方地平线上冉冉升起的朝阳,散发出充满能量的十字光茫，金色和红色的分割寓含“财富、真爱、健康和快乐的平衡”",
            "type"=>2,
        ],
        15=>[
            "id"=>15,
            "title"=>"东方证券的品牌特质是什么？",
            "subject"=>["专业","进取","有温度","值得信赖"],
            "answer"=>"0,1,2,3",
            "tips"=>"",
            "type"=>2,
        ],
        16=>[
            "id"=>16,
            "title"=>"东方证券核心价值观包含以下哪几点？",
            "subject"=>["开拓创新","客户至上","以人为本","专业服务"],
            "answer"=>"0,1,2,3",
            "tips"=>"",
            "type"=>2,
        ],
        17=>[
            "id"=>17,
            "title"=>"东方证券的使命是______________________。",
            "subject"=>["为实体经济、社会财富管理提供优质综合金融服务","为员工创造美好生活","为股东、员工、社会实现物质与精神的双重回报"],
            "answer"=>"0,1,2",
            "tips"=>"",
            "type"=>2,
        ],
        18=>[
            "id"=>18,
            "title"=>"东方证券品牌色彩系统由哪些颜色构成？",
            "subject"=>["https://games.jbxiong.com/images/title/181.png","https://games.jbxiong.com/images/title/182.png"],
            "answer"=>"1",
            "tips"=>"东方证券品牌色彩系统以红、金两色为主进行延展,配合黑、灰两色增加质感,与“东方”这个概念相符合，同时传递美好及温暖的品牌形象，使其更具个性及辩识度。",
            "type"=>1,
            "isimg"=>2
        ],
        19=>[
            "id"=>19,
            "title"=>"东方证券的品牌口号是_____________________。",
            "subject"=>["悦享财富之美","悦享投资之美"],
            "answer"=>"1",
            "tips"=>"",
            "type"=>1,
        ],
        20=>[
            "id"=>20,
            "title"=>"2019年，东方证券响应中国证券业协会发布《证券行业文化建设倡议书》，继续推动企业文化建设，创新实践了“变无形为有形，化有形为无形”的文化建设理念。？",
            "subject"=>["正确","错误"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>3,
        ],
        21=>[
            "id"=>21,
            "title"=>"东方证券的H股上市代码是03958。",
            "subject"=>["正确","错误"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>3,
        ],
        22=>[
            "id"=>22,
            "title"=>"东方证券总部设立在上海",
            "subject"=>["正确","错误"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>3,
        ],
        23=>[
            "id"=>23,
            "title"=>"东方证券的注册资本为69.94亿元",
            "subject"=>["正确","错误"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>3,
        ],
        24=>[
            "id"=>24,
            "title"=>"东方证券提供证券、期货、资产管理、理财、投行、投资咨询及证券研究等全方位、一站式专业综合金融服务的证券金融控股集团。",
            "subject"=>["正确","错误"],
            "answer"=>"0",
            "tips"=>"",
            "type"=>3,
        ],
    ];

    private $ktm = [
        "id"=>1,
        "title"=>"",
        "subject"=>["",""],
        "answer"=>"0",
        "tips"=>"",
        "type"=>1
    ];

    /**
     *获得所有题目
     */
    public function get_alls()
    {
        $this->returnMsg(1, '添加成功',$this->tm);
    }


    /**
     * 获得题目详情
     */
    public function get_subject_info()
    {
        $staff_id = input('staff_id/s', '');
        $subject_id = input('subject_id', 1);
        $token = input('token/s', '');
        $rule = [
            'token' => 'require|length:1,200',
        ];

        $msg = [
            'token.require' => '获取用户信息失败',
            'token.length' => '获取用户信息失败！',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check(['token' => $token]);
        if (!$result) {
            $this->returnMsg(-1, $validate->getError(), []);
        }


        //当前时间
        $today_time = date('Y-m-d 00:00:00',time());
        $cur_time = strtotime($today_time);

        if($cur_time<$this->Start_Day) {
            $data = ['subject' => [], 'status' => 6];
            $this->returnMsg(-1, '活动未开始', $data);
        }

        if($cur_time>$this->End_Day) {
            $data = ['subject' => [], 'status' => 7];
            $this->returnMsg(-1, '活动已经结束', $data);
        }

        if($this->is_holiday()){
            $data = ['subject' => $this->ktm, 'status' => 8];
            $this->returnMsg(-1, '节假日不答题', $data);
        }

        //差距时间
//        $diff_day = ceil((time()-$this->Start_Day)/86400);
//        if($subject_id && $subject_id>0) {
//            $diff_day = $subject_id;
//        }

        $diff_day = $this->get_holiday_to_tm();
        if(!$diff_day || $diff_day<0){
            $data = ['subject' => [], 'status' => 7];
            $this->returnMsg(-1, '活动已经结束.', $data);
        }


        if(!isset($this->tm[$diff_day])){
            $data = ['subject' => [], 'status' => 7,'subject_id'=>$diff_day];
            $this->returnMsg(-1, '活动已经结束..', $data);
        }

        $tm_info = $this->tm[$diff_day];
        $status = 1;


        $user_info = $this->get_user_info($token);
        if(!$user_info){
            $data = ['subject' => [], 'status' => 9];
            $this->returnMsg(-1, '没有找到用户信息', $data);
        }

        $staff_id = $user_info['memberId'];
        $staff_name = $user_info['memberName'];


        $answer_num = Db::name('df_subject_histroy')->where(['staff_id' => $staff_id, 'status' => 1])->count();
        $histroy = Db::name('df_subject_histroy')->where(['staff_id'=>$staff_id,'subject_id'=>$diff_day,'add_time'=>$today_time])->find();
        $last_day = strtotime(date('Y-m-d 00:00:00', $this->End_Day));
        if($histroy) {
            if ($histroy['status'] == 1) {
                //答题对
                $status = 2;
            } else if ($histroy['status'] == 2) {
                //答题对
                $status = 3;
            }

            //如果是最后一天
            $last_day = strtotime(date('Y-m-d 00:00:00', $this->End_Day));
            if ($cur_time == $last_day) {

                if ($answer_num >= 15) {
                    $status = 4;
                } else {
                    $status = 5;
                }
            }

        }



        //status  1-今日未开始 2-今日答题成功 3-今日答题失败 4-闯关成功 5-闯关失败 6-活动未开始 7-活动已经结束
        $tm_info['answer'] = -1;
        //正确答题


        $total_day = 23;
        $data = ['subject'=>$tm_info,'status'=>$status,"diff_day"=>$diff_day,"ok_num"=>$answer_num,"fail_num"=>$diff_day-$answer_num,'total_day'=>$total_day,'last_day'=>$last_day];
        $this->returnMsg(1, '添加成功',$data);
    }

    /**
     *回答问题
     */
    public function answer_subject()
    {
        $staff_id = input('staff_id/s', '');
        $subject_id = input('subject_id/d', 0);
        $anwer = input('answer');
        $token = input('token/s','');
        $rule = [
            'subject_id' => 'require|number',
            'token' => 'require|length:1,200',
        ];

        $msg = [
            'token.require' => '获取用户信息失败',
            'token.length' => '获取用户信息失败！',
            'subject_id.require' => 'subject_id参数错误',
            'subject_id.length' => 'subject_id参数格式错误',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check(['token' => $token, 'subject_id' => $subject_id]);
        if (!$result) {
            $this->returnMsg(-1, $validate->getError(), []);
        }

        $today_time = date('Y-m-d 00:00:00',time());
        $cur_time = strtotime($today_time);
//        $cur_max = ceil(($this->End_Day - $this->Start_Day)/86400);
        if($cur_time<$this->Start_Day) {
            $data = ['subject' => [], 'status' => 6];
            $this->returnMsg(-1, '活动未开始', $data);
        }

        if($cur_time>$this->End_Day) {
            $data = ['subject' => [], 'status' => 7];
            $this->returnMsg(-1, '活动已经结束', $data);
        }

        //差距时间
//        $diff_day = ceil(($cur_time-$this->Start_Day)/86400);
//        if($subject_id && $subject_id>0) {
//            $diff_day = $subject_id;
//        }

        $diff_day = $this->get_holiday_to_tm();

        $tm_info = $this->tm[$diff_day];
        if(!$tm_info){
            $this->returnMsg(-1, '题目不存在', []);
        }

        $user_info = $this->get_user_info($token);
        if(!$user_info){
            $data = ['subject' => [], 'status' => 9];
            $this->returnMsg(-1, '没有找到用户信息', $data);
        }

        $staff_id = $user_info['memberId'];
        $staff_name = $user_info['memberName'];

        $today_time = date('Y-m-d 00:00:00',time());
        $histroy = Db::name('df_subject_histroy')->where(['staff_id'=>$staff_id,'subject_id'=>$tm_info['id'],'add_time'=>$today_time])->find();
        if($histroy){
            $this->returnMsg(-1, '今日已答题', []);
        }



        $status = 1;
        $is_ok = 1;
        if($tm_info['answer'] == $anwer){
            $status = 2;
            $is_ok = 1;
        }
        else {
            $status = 3;
            $is_ok = 2;
        }
        Db::name('df_subject_histroy')->insert(['staff_id'=>$staff_id,'subject_id'=>$tm_info['id'],'add_time'=>$today_time,'status'=>$is_ok,'staff_name'=>$staff_name,'timex'=>date('Y-m-d H:i:s',time())]);

        $last_day = strtotime(date('Y-m-d 00:00:00', $this->End_Day));
//        echo '$last_day='.$last_day.'$cur_time='.$cur_time;
        $answer_num = Db::name('df_subject_histroy')->where(['staff_id' => $staff_id,'status'=>1])->count();
        if ($cur_time == $last_day) {
            $answer_num = Db::name('df_subject_histroy')->where(['staff_id' => $staff_id,'status'=>1])->count();
//            $answer_num = 16;
            if ($answer_num >= 15) {
                $status = 4;
            } else {
                $status = 5;
            }
        }

        $data = ['subject' => $tm_info, 'status' => $status,'ok_num'=>$answer_num,'anwer'=>$anwer];
        $this->returnMsg(1, '添加成功', $data);
    }

    /**
     * 提交信息
     */
    public function submit_msg()
    {
        $names = input('names/s', '');
        $mobile = input('mobile/s', '');
        $address = input('address/', '');
        $token = input('token/s', '');
        $rule = [
            'names' => 'require|length:1,50',
            'mobile' => 'require|length:10,12',
            'address' => 'require|length:2,120',
            'token'=>'require|length:1,200'
        ];

        $msg = [
            'token.require' => '获取用户信息失败',
            'token.length' => '获取用户信息失败！',
            'names.require' => '请输入您的名字！',
            'names.length' => '请输入2字以上的名字！',
            'mobile.require' => '请输入您的手机号码！',
            'mobile.length' => '您的手机号码格式不对！',
            'address.require' => '请输入您的地址！',
            'address.length' => '您的地址格式不对！',
        ];



        $add_data = ['token' => $token, 'names' => $names, 'mobile' => $mobile, 'address' => $address];
        $validate = new Validate($rule, $msg);
        $result = $validate->check($add_data);
        if (!$result) {
            $this->returnMsg(-1, $validate->getError(), []);
        }

        $user_info = $this->get_user_info($token);
        if(!$user_info){
            $data = ['subject' => [], 'status' => 9];
            $this->returnMsg(-1, '没有找到用户信息', $data);
        }

        $staff_id = $user_info['memberId'];
        $add_data = ['staff_id' => $staff_id, 'names' => $names, 'mobile' => $mobile, 'address' => $address];

        $add_data['addtime'] = date('Y-m-d H:i:s');
        $rs = Db::name('df_submit')->insert($add_data);
        $this->returnMsg(1, '添加成功', $rs);
    }

    /**
     * 获得题目详情
     */
    public function get_subject_info_test()
    {
        $staff_id = input('staff_id/s', '');
        $subject_id = input('subject_id/', 1);
        $rule = [
            'staff_id' => 'require|length:1,50',
        ];

        $msg = [
            'staff_id.require' => '参数错误',
            'staff_id.length' => '参数过长',
        ];

        $validate = new Validate($rule, $msg);
        $result = $validate->check(['staff_id' => $staff_id]);
        if (!$result) {
            $this->returnMsg(-1, $validate->getError(), []);
        }

        //当前时间
        $today_time = date('Y-m-d 00:00:00',time());
        $cur_time = strtotime($today_time);



        //差距时间
        $diff_day = ceil(($cur_time-$this->Start_Day)/86400);

        $tm_info = $this->tm[$subject_id];
        $status = 1;
        $histroy = Db::name('df_subject_histroy')->where(['staff_id'=>$staff_id,'subject_id'=>$diff_day,'add_time'=>$today_time])->find();
        if($histroy) {
            if ($histroy['status'] == 1) {
                //答题对
                $status = 2;
            } else if ($histroy['status'] == 2) {
                //答题对
                $status = 3;
            }

            //如果是最后一天
            if($cur_time == $this->End_Day) {
                $answer_num = Db::name('df_subject_histroy')->where(['staff_id' => $staff_id,'status'=>1])->count();
                if ($answer_num > 15) {
                    $status = 4;
                } else {
                    $status = 5;
                }
            }
        }



        //status  1-今日未开始 2-今日答题成功 3-今日答题失败 4-闯关成功 5-闯关失败 6-活动未开始 7-活动已经结束
        $tm_info['answer'] = -1;
        //正确答题
        $answer_num = Db::name('df_subject_histroy')->where(['staff_id' => $staff_id,'status'=>1])->count();
        $total_day = 24;
        $data = ['subject'=>$tm_info,'status'=>$status,"diff_day"=>$diff_day,"ok_num"=>$answer_num,"fail_num"=>$diff_day-$answer_num,'total_day'=>$total_day];
        $this->returnMsg(1, '添加成功',$data);
    }

    public function get_user_info_test($token){

        $res = Post([],'https://kldf.dfzq.com.cn/dfzq-journey/getUserInfo.htm?vhstoken=9ed14a619fb14036ad788dbf555c1ab6');
//        $res = Post_Test([],"https://kldf.dfzq.com.cn/dfzq-journey/getUserInfo.htm?vhstoken=$token",["Content-Type:application/json;charset=utf-8"],10);
        $this->returnMsg(1, '添加成功',$res);
    }

    private function get_user_info($token)
    {
//        $res = Post([],'https://kldf.dfzq.com.cn/dfzq-journey/getUserInfo.htm?vhstoken=9ed14a619fb14036ad788dbf555c1ab6');
        $token_info = Db::name('df_tokens')->where(['token' => $token])->find();
        if ($token_info) {
            return $token_info;
        } else {
            $send_url = "https://kldf.dfzq.com.cn/dfzq-journey/getUserInfo.htm?vhstoken=$token";
            $res = Post_Test([], $send_url, ["Content-Type:application/json;charset=utf-8"], 10);
            if (!$res)
                return null;

            $res = json_decode($res, true);
            if (!$res || $res['code'] != 200 || !$res['extenal'])
                return null;

            $memberId = $res['extenal']['memberId'];
            $memberName = $res['extenal']['memberName'];
            $work_no = $res['extenal']['workNo'];
            $dept_code = $res['extenal']['deptCode'];
            $dept_name = $res['extenal']['deptName'];

            Db::name('df_tokens')->insert(['token' => $token, 'add_time' => time(), 'memberId' => $memberId, 'memberName' => $memberName,'work_no'=>$work_no,'dept_code'=>$dept_code,'dept_name'=>$dept_name]);
//            Db::name('df_tokens')->insert(['token' => $token, 'add_time' => time(), 'memberId' => $memberId, 'memberName' => $memberName]);
            return $res['extenal'];
        }
    }

    /**
     *获得放假日期
     */
    public function get_holiday(){
        $timestamp1=$this->Start_Day;
        $timestamp2=$this->End_Day;
        $days=($timestamp2-$timestamp1)/86400+1;
        $date=[];


        $tm_total = 0;
//		for($i=0;$i<$days;$i++) {
//            $day_time = $timestamp1 + (86400 * $i);
//            $times = date('Y-m-d', $day_time);
//            $xqj = date("w", $day_time);
//
//            if (in_array($times, $this->gq_arr)) {
//                continue;
//            }
//
//            if ($xqj == 6 || $xqj == 0) {
//                continue;
//            }
//            $tm_total+=1;
//            $date[] = ['times' => $times, 'day' => $xqj];
//
//        }

        $date['tm_total'] = $tm_total;
        $date['days'] = $days;
        $date['get_holiday_to_tm'] = $this->get_holiday_to_tm();
        $this->returnMsg(1, '添加成功',$date);
    }

    /**
     * 扣掉假期计算答题编号
     */
    private function get_holiday_to_tm()
    {
        $timestamp1 = $this->Start_Day;
        $timestamp2 = strtotime(date('Y-m-d', time()));
        $days = floor(($timestamp2 - $timestamp1) / 86400) + 1;


        $tm_total = 0;
        for ($i = 0; $i < $days; $i++) {
            $day_time = $timestamp1 + (86400 * $i);
            $times = date('Y-m-d', $day_time);
            $xqj = date("w", $day_time);

            if (in_array($times, $this->gq_arr)) {
                continue;
            }

            if ($xqj == 6 || $xqj == 0) {
                continue;
            }
            $tm_total += 1;
        }

        return $tm_total;
    }

    /**
     * 是否是假期
     * @return bool
     */
    private function is_holiday(){
        $day_time = time();
        $times = date('Y-m-d', $day_time);
        $xqj = date("w", $day_time);

        if (in_array($times, $this->gq_arr)) {
            return true;
        }

        if ($xqj == 6 || $xqj == 0) {
            return true;
        }

        return false;
    }
}
